<template>
  <el-dialog title="选择展示字段" :visible.sync="show" :close-on-click-modal="false" width="800px" @closed="closed">
    <div class="title-box">
      <el-button type="text" @click="checkAll(true)">全选</el-button>
      <el-button type="text" @click="checkAll(false)">全不选</el-button>
    </div>
    <div class="list">
      <div class="item ellipsis" v-for="item in list" :key="item.value">
        <el-checkbox v-model="item.checked">{{ item.label }}</el-checkbox>
      </div>
    </div>
    <div slot="footer">
      <el-button type="primary" @click="btnSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { debounce } from '@/utils'
import { fieldList } from './fieldList'
export default {
  data() {
    return {
      show: false,
      list: [],
      isConfirm: false
    }
  },
  created() {
    this.btnSubmit = debounce(this.onSubmit, 1e3, true)
    const list = JSON.parse(JSON.stringify(fieldList))
    list.map(i => (i.checked = false))
    this.list = list
  },
  methods: {
    open(selected = []) {
      this.show = true
      this.list.map(i => (i.checked = selected.includes(i.value)))
    },
    checkAll(checked) {
      this.list.map(i => (i.checked = checked))
    },
    onSubmit() {
      this.isConfirm = true
      this.show = false
    },
    closed() {
      // 关闭后再执行 emit，解决选择字段太多导致弹窗关闭卡住
      if (!this.isConfirm) return
      this.isConfirm = false
      const selected = this.list.filter(i => i.checked).map(i => i.value)
      this.$emit('selected', selected)
    }
  }
}
</script>
<style lang="scss" scoped>
.title-box {
  .text {
    font-weight: bold;
    margin-right: 10px;
  }
}
.list {
  display: flex;
  flex-wrap: wrap;
}
.item {
  width: 20%;
  padding-right: 10px;
  cursor: default;
}
</style>
